//app.js

App({
	onLaunch: function () {
		let that = this;
		//调用API从本地缓存中获取数据
		var logs = wx.getStorageSync('logs') || []
		logs.unshift(Date.now())
		wx.setStorageSync('logs', logs);
		//授权后开始登陆
		wx.getSetting({
			success(res) {
				if (res.authSetting['scope.userInfo']) {
					that.getUserInfo();
				}
			}
		})
	},
	getUserInfo: function (cb) {
		var that = this;
		wx.login({
			success: function (res) {
				var code = res['code'];
				//2.小程序调用wx.getUserInfo得到rawData, signatrue, encryptData.
				wx.getUserInfo({
					success: function (info) {
						var rawData = info['rawData'];
						var signature = info['signature'];
						var encryptData = info['encryptData'];
						var encryptedData = info['encryptedData'];
						var iv = info['iv'];
						wx.request({
							url: that.globalData.url + 'login',
							data: {
								"code": code,
								"rawData": rawData,
								"signature": signature,
								"encryptData": encryptData,
								'iv': iv,
								'encryptedData': encryptedData
							},
							success: function (res) {
								//将用户数据存于缓存中
								wx.setStorage({
									key: 'userInfo',
									data: res.data,
								})

								that.globalData.userInfo = res;
								typeof cb == "function" && cb(that.globalData.userInfo)
								wx.hideLoading()
							}
						});
					}
				});

			}
		});
	},
	//其他页面调用登陆功能
	login: function (cb) {
		let that = this;
		that.getUserInfo();
		//首选询问是否登陆，如果没有登陆的话就跳转到个人中心页面
		wx.getSetting({
			success(res) {
				//没有授权
				if (!res.authSetting['scope.userInfo']) {
					console.log('没有授权');
					wx.showModal({
						title: '提示',
						content: '您还没有授权本应用，请先点击登录完成授权',
						showCancel: false,
						success: function (res) {
							wx.reLaunch({
								url: '../my/index'
							})
						}
					})
					return false;
				}else{
					//读取用户信息缓存，避免每次都要刷新
					that.catchUserInfo(cb);
				}
			}
		})
		
	},
	// 此方法没有登录状态下不会强制跳转授权
	login_canno: function (cb) {
		let that = this;
		that.getUserInfo();

		//读取用户信息缓存，避免每次都要刷新
		that.catchUserInfo(cb);
	},
	catchUserInfo(cb) {
		let that = this;
		wx.getStorage({
			key: 'userInfo',
			success: function (res) {
				var userInfo = res;
			
				//容错机制
				setTimeout(function () {
					wx.getStorage({
						key: 'userInfo',
						success: function (res) {
							if (res.data.nickName != userInfo.data.nickName || res.data.qianming != userInfo.data.qianming || res.data.avatarUrl != userInfo.data.avatarUrl || res.data.birthday != userInfo.data.birthday || res.data.gender != userInfo.data.gender || res.data.money != userInfo.data.money || res.data.mobile != userInfo.data.mobile) {
								console.log("容错一次");
								that.login(cb);
							}
							//console.log(res.data);
						}
					})
				}, 1400);
				//执行传进了的函数
				typeof cb == "function" && cb(userInfo)
			},
			fail: function () {
				
				//执行传进了的函数
				typeof cb == "function" && cb()
			}
		})
	},
	globalData: {
		url: 'https://facescore.maggie.vip/facescore/',
		siteroot: 'https://facescore.maggie.vip',
		userInfo: null
	},
	//參數分別是 地址，傳入參數，成功后執行函數
	connect: function (url, parameter, callback, types = false) {
		let that = this;
		if (types) {
			wx.showLoading({
				title: '加载中...',
			})
		}
		wx.request({
			url: that.globalData.url + url, //仅为示例，并非真实的接口地址
			data: parameter,
			dataType: 'json',
			method: "POST",
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: function (res) {
				if (types) {
					wx.hideLoading()
				}
				callback(res.data);

				//console.log(res.data);
			}
		})
	},
	//获取access_token
	getToken: function () {
		var that = this;
		that.connect("getToken.php", "", function (e) {
			that.globalData.token = e;
		});
	},
	isNumber: function (n) {
		return !isNaN(parseFloat(n)) && isFinite(n);
	},
	//批量上传图片函数
	uploadimg: function (data) {
		var that = this,
			i = data.i ? data.i : 0,
			success = data.success ? data.success : 0,
			fail = data.fail ? data.fail : 0;
		const uploadTask = wx.uploadFile({
			url: data.url,
			filePath: data.path[i].path,
			name: 'sendImg',
			formData: {
				uid: data.data.uid,
				openid: data.data.openid,
				content_id:data.data.content_id,
				type: data.path[i].type
			},
			success: (resp) => {
				success++;
				console.log(resp)
			},
			fail: (res) => {
				fail++;
				console.log('fail:' + i + "fail:" + fail);
			},
			complete: () => {
				i++;
				if (i == data.path.length) {  //当图片传完时，停止调用    
					console.log('执行完毕');
					console.log('成功：' + success + " 失败：" + fail);
					return true;
				} else {
					data.i = i;
					data.success = success;
					data.fail = fail;
					that.uploadimg(data);
				}

			}
		});
		uploadTask.onProgressUpdate((res) => {
			console.log('上传进度', res.progress)
			console.log('已经上传的数据长度', res.totalBytesSent)
			console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
		})

	},
	isPoneAvailable:function(str) {
		var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
		if (!myreg.test(str)) {
			return false;
		} else {
			return true;
		}
	},
	checkMobile:function(userInfo){
		if(!this.isPoneAvailable(userInfo.mobile)) {
			// wx.showModal({
			// 	title: '提示',
			// 	content: '请先绑定手机号后再进行操作',
			// 	showCancel: false,
			// 	success: function (res) {
					wx.reLaunch({
						url: '../login/index'
					})
			// 	}
			// })
		}
		
	}
})